<template>
    <div>
        <div class="row mb-1">
            <div class="col">
                <el-form :inline="true">
                    <el-form-item label="团队">
                        <el-select v-model="teamid" multiple collapse-tags filterable>
                            <el-option v-for="item in getteam" :key="item.ID" :label="item.name"
                                :value="Number(item.ID)"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="团员">
                        <el-select v-model="userids" collapse-tags multiple filterable>
                            <el-option v-for="item in getusers" :key="Number(item.ID)" :label="String(item.name)"
                                :value="Number(item.ID)"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="答题时间">
                        <el-date-picker v-model="times" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间"
                            :shortcuts="shortcuts">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="题单ID">
                        <el-input v-model.number="questionbankid" placeholder="请输入题单ID"></el-input>
                    </el-form-item>
                    <el-form-item label="题单模式">
                        <el-select v-model="questionbanktype">
                            <el-option label="全部" :value="0"></el-option>
                            <el-option label="练习模式" :value="1"></el-option>
                            <el-option label="测评模式" :value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="附加信息">
                        <el-select v-model="attr" multiple collapse-tags filterable>
                            <el-option label="团队名称" value="团队名称"></el-option>
                            <el-option label="手机号" value="手机号"></el-option>
                            <el-option label="学校" value="学校"></el-option>
                            <el-option label="姓名" value="姓名"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="总条数：">{{ count1 }} </el-form-item>
                            <el-form-item label="用户数">{{ userids.length }} </el-form-item>
                        </el-col>
                        <el-col :span="12" class="text-right">
                            <el-button type="primary" @click="start">查询</el-button>
                            <el-button type="primary" @click="() => download()">下载</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

        </div>
        <div class="row mb-1">
            <div class="col">
                <el-table :data="questions" border height="65vh" style="width: 100%">
                    <el-table-column prop="name" label="用户" width="120">
                    </el-table-column>
                    <el-table-column prop="questionbankid" label="题单ID" width="100">

                    </el-table-column>

                    <el-table-column prop="teamname" label="团队名称">
                    </el-table-column>
                    <el-table-column prop="xingming" label="姓名" width="150">
                    </el-table-column>
                    <el-table-column prop="phonenum" label="手机号" width="150">
                    </el-table-column>
                    <el-table-column prop="resultdataarr" label="学校" width="150">
                        <template #default="scope">
                            {{ scope.row.info?.school }}
                        </template>
                    </el-table-column>
                    <el-table-column :prop="String(v)" :label="String(v)" v-for="v in keys" width="350">
                    </el-table-column>
                </el-table>
            </div>
        </div>

        <div class="row mb-1">
            <div class="col">
                <el-pagination :page-size="limit" :total="count1" @size-change="handleSizeChange" @current-change="change"
                    layout="sizes, prev, pager, next" :current-page="Math.floor(offset / limit) + 1"></el-pagination>
            </div>
        </div>
    </div>
</template>
  
<script lang="ts" setup>
import {
    Iobj,
    asyncselectuserquestionbank,
    asyncselectteamuser,
    asyncgetquestionbank,
} from "../../../api";
import { ElMessage } from "element-plus";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import {
    computed,
    inject,
    onMounted,
    onUnmounted,
    ref,
    watch,
} from "vue";
import { onBeforeRouteUpdate, useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { TimeYH } from "../../../util/time";
import { once, uniq } from "underscore";

import { Storekey } from "../../../interface";
import { getExceltodownload } from "../../../util/excel";
import moment from "moment";


const attr = ref<string[]>([])

const limit = computed(() => {
    return Number(roue.value.limit) || 20;
});
const handleSizeChange = (val: number) => {
    router.push({
        query: {
            ...roue.value,
            limit: val
        }
    })
}
const offset = computed(() => {
    return Number(roue.value.offset) || 0;
});
const userquestion = ref<Studycodemodel.Iuser[]>([]);
const route = useRoute();
const router = useRouter();
const roue = computed(() => {
    return route.query;
});
const count1 = ref(0);

const store = useStore(Storekey);
const getteam = computed<Studycodemodel.Iteam[]>(() => {
    return store.getters.getteam;
});
const getusers = ref<Array<Studycodemodel.Iuser>>([]);
const headnavdialogVisible = inject("headnavdialogVisible", () => { });
const user = computed<Studycodemodel.Iuser | undefined>(() => {
    return store.getters.getuser;
});
const times = ref<[number, number]>([Date.now() - 1000 * 60 * 60 * 24 * 7, Date.now()]);
const height = ref(window.innerHeight - 74);
function onresize(e: UIEvent) {
    height.value = window.innerHeight - 74;
}
window.onresize = onresize;


const isad = computed(() => {
    return Number(roue.value.isad) || 0;
});

const questionid = ref<number>();
const teamid = ref<number[]>([]);
const userids = ref<Array<number | undefined>>([]);
const questionbanktype = ref<number>(0);
onUnmounted(() => {
    window.onresize = () => { };
});

const questionbank = ref<Studycodemodel.Iquestionbank>()

const keys = computed(() => {
    return questionbank.value?.questionquestionbank?.sort((c) => {
        return c.sortindex
    }).map(e => {
        return e.questionid
    }) || []
})

const questions = computed(() => {
    return userquestion.value.map(e => {
        const data: Record<any, string> = {

        }

        e.userquestion?.forEach(c => {
            const { resultdata, resultdataarr, questionid } = c
            if (data[questionid]) {
                data[questionid] = `${data[questionid]} {[${resultdata}], ${resultdataarr?.join(',')}}`
            } else {
                data[questionid] = `{[${resultdata}], ${resultdataarr?.join(',')}}`
            }
        })
        return {
            ...e,
            ...data,
            questionbankid: questionbankid.value
        }
    })
})

onBeforeRouteUpdate(() => {
    questionid.value = Number(roue.value.questionid);
    questionbankid.value =
        (roue.value.questionbankid as unknown as number) || undefined;
    start();
});

const questionbankid = ref<number>();

async function start() {
    if (!user.value) {
        headnavdialogVisible();
        return;
    }
    if (
        !isad.value &&
        [questionbankid.value, userids.value.length].filter((e) => e)
            .length === 0
    ) {
        ElMessage.error("请输入题单");
        return;
    }

    const userid = userids.value;
    const Iobj: Studycodemodel.Iuserquestion = {
        userid
    };
    if (times.value) {
        Iobj.createdAt = {
            lt: times.value[1],
            gt: times.value[0],
        };
    }
    if (questionbanktype.value === 1) {
        Iobj.testid = {
            is: null,
        };
    }
    if (questionbanktype.value === 2) {
        Iobj.testid = {
            not: null,
        };
    }

    if (questionbankid.value) {
        Iobj.questionbankid = questionbankid.value;
    }
    if (questionid.value) {
        Object.assign(Iobj, {
            questionid: questionid.value,
        });
    }

    // questionbank.value = await asyncgetquestionbank({
    //     ID: questionbankid.value
    // })

    const data = await asyncselectuserquestionbank(
        Object.assign(Iobj)
    );
    count1.value = data.length;
    userquestion.value = data

}

onMounted(() => {
    try {
        store.dispatch("actionteam");
    } catch (e: any) {
        ElMessage.error(e);
    }
    questionid.value = Number(roue.value.questionid) || undefined
    teamid.value = roue.value.teamid ? [Number(roue.value.teamid)] : []
    questionbankid.value = Number(roue.value.questionbankid as unknown as number) || undefined
});

function change(r: number) {
    router.push({
        name: "题单记录",
        query: {
            questionbankid: questionbankid.value,
        },
    });
}

const onc = once(start);

watch(
    () => teamid.value,
    (n) => {
        if (n) {
            const team = getteam.value.find((e) => teamid.value.includes(e.ID));
            asyncselectteamuser({
                teamid: n,
                _limit: 999999
            }).then((e) => {
                const { rows } = e;
                getusers.value = rows.map((v) => {
                    const { user, username } = v;
                    if (username && user) {
                        user.name = username;
                    }
                    return user as Studycodemodel.Iuser;
                });
                if (team && team.user) {
                    getusers.value.push(team.user);
                }
                userids.value = getusers.value.map((v) => v?.ID);
                onc();
            });
        } else {
            getusers.value = [];
            userids.value = [];
        }
    }
);



function download() {
    const data1: string[][] = [
        ["用户", "题单ID", '团队名称', '手机号', '姓名', '学校'].concat(...keys.value),
    ];

    questions.value.forEach((e) => {
        let {
            name,
            questionbankid,
            teamname,
            xingming,
            phonenum,
            info
        } = e;
        data1.push([
            String(name),
            String(questionbankid),
            String(teamname),
            String(phonenum),
            String(xingming),
            String(info?.school),
        ].concat(...keys.value?.map(t => e[String(t)]))
        );
    });


    if (data1.length > 1) {
        const n: Record<string, number> = {
            团队名称: 2,
            手机号: 3,
            姓名: 4,
            学校: 5,
        }
        attr.value.forEach(c => {
            console.log(c)
            delete n[c]
        })
        const n1 = Object.values(n)
        const t = data1.map(c => {
            const data: string[] = []
            c.forEach((e, k) => {
                if (!n1.includes(k)) {
                    data.push(e)
                }
            })
            return data
        })
        getExceltodownload(t, "学生答题信息");
    }
}



const shortcuts = [
    {
        text: "上周",
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            return [start, end];
        },
    },
    {
        text: "本周",
        value: () => {
            const end = new Date();

            const start = moment().day(1).unix() * 1000;
            return [start, end];
        },
    },
    {
        text: "本月",
        value: () => {
            const end = new Date();
            const start = moment().date(1).unix() * 1000;
            return [start, end];
        },
    },
    {
        text: "最近90天",
        value: () => {
            const end = new Date();
            const start = moment().date(-90).unix() * 1000;
            return [start, end];
        },
    },
]


</script>
  
<style scoped>
.gre {
    background-color: var(--color-cheng);
    color: #fff;
}

.gre:hover {
    background-color: var(--color-cheng);
    color: #fff;
}

.gre:active {
    background-color: var(--color-cheng);
    color: #fff;
}

.gre:focus {
    background-color: var(--color-cheng);
    color: #fff;
}

.Accepted {
    color: #53c419;
}

.Unaccepted {
    color: #9d3dcf;
}

.CompileError {
    color: #e74b3c;
}

/* .Unshown {
  
  } */
</style>
  
  